package com.bjpowernode.gateway.mvc.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjpowernode.gateway.common.enums.TradeStatus;
import com.bjpowernode.gateway.common.util.SignUtil;
import com.bjpowernode.gateway.common.util.kq.KqUtil;
import com.bjpowernode.gateway.db.domain.PayWay;
import com.bjpowernode.gateway.db.domain.TradeOrder;
import com.bjpowernode.gateway.db.domain.UserPayConfig;
import com.bjpowernode.gateway.db.domain.UserPayInfo;
import com.bjpowernode.gateway.db.mapper.PayWayMapper;
import com.bjpowernode.gateway.db.mapper.TradeOrderMapper;
import com.bjpowernode.gateway.db.mapper.UserPayConfigMapper;
import com.bjpowernode.gateway.db.mapper.UserPayInfoMapper;
import com.bjpowernode.gateway.mvc.models.form.TradeReceiveForm;
import com.bjpowernode.gateway.mvc.models.form.QueryOrderForm;
import com.bjpowernode.gateway.mvc.service.PaymentTradeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class PaymentTradeServiceImpl implements PaymentTradeService {

    @Resource
    UserPayConfigMapper userPayConfigMapper;

    @Resource
    PayWayMapper payWayMapper;

    @Resource
    TradeOrderMapper tradeOrderMapper;

    @Resource
    UserPayInfoMapper userPayInfoMapper;

    @Override
    public List<PayWay> checkRequestSignGetPayWayList(TradeReceiveForm receiveForm) {
        //1.查询支付方式是否存在
        UserPayConfig userPayConfig = userPayConfigMapper.selectOne(receiveForm.getUserNo(),receiveForm.getPayProductCode(),receiveForm.getAppKey());
        if(userPayConfig==null){
            throw new RuntimeException("商户配置无效");
        }
        //2.验证签名
        boolean check = SignUtil.checkSign(JSONUtil.toBean(JSONUtil.toJsonPrettyStr(receiveForm), Map.class),userPayConfig.getAppSecret(),receiveForm.getSign());
        //3.查询支付方式
        List<PayWay> payWays =  payWayMapper.selectList(new QueryWrapper<PayWay>().eq("pay_product_code",receiveForm.getPayProductCode()).orderByAsc("way_code"));
        return payWays;
    }

    @Override
    public String obtainResult(String json) {
        //查询订单
        QueryOrderForm bean = JSONUtil.toBean(json, QueryOrderForm.class);
        QueryWrapper<TradeOrder> queryTradeOrder = new QueryWrapper<>();
        queryTradeOrder.eq("user_no",bean.getUserNo()).eq("user_order_no",bean.getOrderNo());
        TradeOrder tradeOrder = tradeOrderMapper.selectOne(queryTradeOrder);
        if(tradeOrder==null){
            throw new RuntimeException("不存在订单");
        }
        //查询支付配置
        QueryWrapper<UserPayConfig> queryPayConfig = new QueryWrapper<>();
        queryTradeOrder.eq("app_key",bean.getAppKey());
        UserPayConfig config = userPayConfigMapper.selectOne(queryPayConfig);
        if(config==null){
            throw new RuntimeException("不存在支付配置信息");
        }
        //验证签名
        Map<String,String> map = JSONUtil.toBean(json,Map.class);
        boolean checkSign = SignUtil.checkSign(map,bean.getAppKey(), bean.getSign());
        checkSign = true;
        if(!checkSign){
            throw new RuntimeException("验证签名失败");
        }
        JSONObject object = new JSONObject();
        if(TradeStatus.CREATE.name().equals(tradeOrder.getStatus())){
            QueryWrapper<UserPayInfo> queryPayInfo = new QueryWrapper<>();
            queryPayInfo.eq("user_no",config.getUserNo()).eq("pay_product_code",config.getPayProductCode()).eq("pay_way_code",tradeOrder.getPayWayCode());
            UserPayInfo info =  userPayInfoMapper.selectOne(queryPayInfo);
            if(info==null){
                throw new RuntimeException("不存在支付信息");
            }
            String payConfig = info.getPayConfig();
            JSONObject obj = JSONUtil.parseObj(payConfig);
            String response = KqUtil.queryOrder(obj.getStr("merchId"),tradeOrder.getTxNo(), obj.getStr("privateFile"), obj.getStr("queryKey"));
            if("error".equals(response)|| StrUtil.isBlank(response)){
                object.set("code",TradeStatus.EXCEPTION.name());
                object.set("msg",TradeStatus.EXCEPTION.getMsg());
            }else{
                TradeStatus tradeStatus = handleQueryResponse(response);
                object.set("code",TradeStatus.EXCEPTION.name());
                object.set("msg",TradeStatus.EXCEPTION.getMsg());
            }
        }else{

        }
        return JSONUtil.toJsonStr(object);
    }

    private TradeStatus handleQueryResponse(String response) {
        JSONObject obj = JSONUtil.parseObj(response);
        JSONArray orderDetailArray = obj.getJSONArray("orderDetail");
        if( JSONUtil.isNull(orderDetailArray)){
            return TradeStatus.WAIT_PAY;
        }
        //获取 订单信息
        JSONObject orderDetail = orderDetailArray.getJSONObject(0);
        String result = orderDetail.getStr("payResult");
        if( "10".equals(result)){
            return TradeStatus.SUCCESS;
        } else {
            return TradeStatus.FAILURE;
        }
    }
}
